package lib

import (
	"encoding/json"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/go-xorm/xorm"
	"io/ioutil"
	"os"
	"xorm.io/core"
)

var dbHandle []*xorm.Engine

type DBList struct {
	DBUser string `json:"db_user"`
	DBHome string `json:"db_home"`
	DBPort int    `json:"db_port"`
	DBName string `json:"db_name"`
	DBPass string `json:"db_pass"`
}

func UseHandle(nIndex int) *xorm.Engine {
	if len(dbHandle) >= nIndex {
		return dbHandle[nIndex]
	}
	return nil
}

func readConfig(filename string) ([]byte, error) {
	jsonFile, err := os.Open(filename)
	if err != nil {
		panic("打开文件错误，请查看：" + filename)
	}
	defer jsonFile.Close()
	return ioutil.ReadAll(jsonFile)
}

func init() {
	var dbList []DBList
	data, err := readConfig("./config/db.json")
	if err != nil {
		panic("读取文件错误：" + err.Error())
	}

	_ = json.Unmarshal(data, &dbList)
	fmt.Println("mysql:连接参数：", dbList)

	for _, db := range dbList {
		strConn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8",
			db.DBUser,
			db.DBPass,
			db.DBHome,
			db.DBPort,
			db.DBName)
		dbHand, err := xorm.NewEngine("mysql", strConn)
		if err != nil {
			panic(err.Error())
		}
		err = dbHand.Ping()
		if err != nil {
			panic(err.Error())
		}
		dbHand.SetTableMapper(core.SnakeMapper{})
		dbHand.SetColumnMapper(core.SnakeMapper{})
		dbHand.ShowSQL(true)
		dbHand.SetMaxIdleConns(5)
		dbHand.SetMaxOpenConns(5)
		dbHandle = append(dbHandle, dbHand)
	}
}
